﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using System.Threading;
using BaseManage.db;

namespace BaseManage.Files
{
    public class FileOperate
    {
        dbOperate dbo = new dbOperate();

        private int TotalCount = 0;//生成总数
        private const string left = "<td style=\"font-size:12; font-weight:bold;text-align:center\">";//左标签
        private const string right = "</td>";//右标签
        private string CreatePath = "";//创建文件路径
        private string ModlePath = "";//模板文件
        private ArrayList FileList = new ArrayList();
        private string FileStr = "";

        private RichTextBox box;
        private ProgressBar bar;
        private Label label;

        private string tempfile = "";
        public FileOperate(RichTextBox box, ProgressBar bar, Label label)
        {
            this.box = box;
            this.label = label;
            this.bar = bar;
            this.bar.Value = 0;
            GetPath();
            ReadModle();
            GetTotalCount();
            this.bar.Maximum = TotalCount;
            this.bar.Minimum = 0;
        }

        //获取生成总数
        private void GetTotalCount()
        {
            //newstr = "获取需生成的页面文件总数......\n";
            box.AppendText("获取需生成的页面文件总数......\n");
            TotalCount = dbo.GetCount("ProductManage", "");
            //newstr = "共需生成" + TotalCount .ToString()+ "个文件\n";
            box.AppendText("共需生成" + TotalCount .ToString()+ "个文件\n");
        }

        //获取相关路径
        private void GetPath()
        {            

            DataSet dt = dbo.GetDataSet("select * from DataTongBu where Condition=1");
            if (dt != null && dt.Tables["data"].Rows.Count > 0)
            {
                box.AppendText("获取文件产生路径和模板文件路径......\n");
                try
                {
                    //CreatePath = dt.Tables["data"].Rows[0][1].ToString();
                    CreatePath =  "\\html";
                    //ModlePath = dt.Tables["data"].Rows[0][2].ToString();
                    ModlePath = "\\template\\template.html";
                    box.AppendText("获取成功\n");
                }
                catch (Exception ex)
                {
                    box.AppendText("获取失败，系统异常：" + ex.Message + "\n");
                }
               
            }
        }

        //读入模板文件
        private void ReadModle()
        {
            CreatePath = Application.StartupPath + "\\html";
            //ModlePath = dt.Tables["data"].Rows[0][2].ToString();
            ModlePath =Application.StartupPath + "\\template\\template.html";
            //MessageBox.Show(ModlePath);
            if (File.Exists(ModlePath))
            {
                try
                {
                    box.AppendText("开始读取模板文件......\n");
                    StreamReader read = new StreamReader(ModlePath, Encoding.GetEncoding("gb2312"));
                    string line = "";
                    while (line != null)
                    {
                        line = read.ReadLine();
                        if (line != null && !line.Equals(""))
                        {
                            FileStr += line;
                            //FileList.Add(line);
                        }
                    }
                    
                    read.Close();
                    box.AppendText("读取成功\n");
                }
                catch (Exception ex)
                {
                    box.AppendText("读取失败，系统异常：" + ex.Message + "\n");
                }
            }
            else
            {
                box.AppendText("没有找到模板文件，请确认路径是否正确\n");
            }
        }

        //文件生成
        /// <summary>
        /// 文件生成规则
        /// 1、路径：应用程序路径\\html\\productcode+productorder
        /// </summary>
        public void CreatrFile()
        {
            DataSet ProductSet = null;//new DataSet();
            DataSet BaseSet = null;//new DataSet();
            /*
            DataSet FeiLiaoSet = new DataSet();
            DataSet NongYaoSet = new DataSet();
            DataSet YangFenSet = new DataSet();
            */
            ProductSet = dbo.GetDataSet("select * from ProductManage");

            if (ProductSet != null && TotalCount > 0)
            {
                string productstr = "";//产品静态页面插入字符串
                string productQR = "";
                //string basestr = "";//基地静态页面插入字符串
                string BaseId = "";
                string BaseCode = "";
                string BaseName = "";
                string BaseScale = "";
                string ProduceType = "";
                string StandardCode = "";
                string PeopleName = "";
                string PhoneNumber = "";
                string BookNumber = "";
                string Address = "";
                
                string feiliaostr = "";//肥料静态页面插入字段
                string nongyaostr = "";//农药静态页面插入字段
                string yangfenstr = "";//养分静态页面插入字段

                string basename = "";//基地名称
                string productname = "";//产品名称

                string waterreport = "";//水检测报告路径
                string airreport = "";//空气检测报告路径
                string soilreport = "";//土壤检测报告路径
                string ferreport = "";//化肥检测报告路径
                string yaoreport = "";//农药检测报告路径
                string checkrecord = "";
                string operaterecord = "";
               

                FileStream fs;
                StreamWriter sw;
                try
                {
                    box.AppendText("文件生成开始......\n");
                    if (!Directory.Exists(CreatePath))//若路径不存在则创建该路径   
                    {
                        Directory.CreateDirectory(CreatePath);   
                    }

                    
                    for (int i = 0; i < TotalCount; i++)
                    {
                        int count = ((i+1) / TotalCount) * 100;
                        this.label.Text = count.ToString() + "%";
                        this.bar.Step = 1;
                        this.bar.PerformStep();
                        productstr = "";//产品静态页面插入字符串
                        //basestr = "";//基地静态页面插入字符串
                        feiliaostr = "";//肥料静态页面插入字段
                        nongyaostr = "";//农药静态页面插入字段
                        yangfenstr = "";//养分静态页面插入字段

                        fs = new FileStream(CreatePath + "\\" + ProductSet.Tables["data"].Rows[i][1].ToString() +ProductSet.Tables["data"].Rows[i]["productorder"].ToString()+ ".html", FileMode.Create);
                        sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
                        basename = ProductSet.Tables["data"].Rows[i][2].ToString();
                        productname = ProductSet.Tables["data"].Rows[i][3].ToString();
                        //创造产品字符串
                        string ProductId = ProductSet.Tables["data"].Rows[i]["id"].ToString();
                        string Code = ProductSet.Tables["data"].Rows[i]["Code"].ToString();
                        string ProductType = ProductSet.Tables["data"].Rows[i]["ProductType"].ToString();
                        string ProductScale = ProductSet.Tables["data"].Rows[i]["ProductScale"].ToString();
                        string ProductCircle = ProductSet.Tables["data"].Rows[i]["ProductCircle"].ToString();
                        string Package = ProductSet.Tables["data"].Rows[i]["Package"].ToString();
                        string YearOutPut = ProductSet.Tables["data"].Rows[i]["YearOutPut"].ToString();
                        string Sales = ProductSet.Tables["data"].Rows[i]["Sales"].ToString();
                        string ProductStandardCode = ProductSet.Tables["data"].Rows[i]["StandardCode"].ToString();
                        string ProductIntroductPath = ProductSet.Tables["data"].Rows[i]["ProductIntroduce"].ToString();
                        string CookTech = ProductSet.Tables["data"].Rows[i]["CookTech"].ToString();
                        string OperateRule = ProductSet.Tables["data"].Rows[i]["OperateRule"].ToString();
                        string QRPath = ProductSet.Tables["data"].Rows[i]["QRFile"].ToString();
                        string ProductOrder = ProductSet.Tables["data"].Rows[i]["ProductOrder"].ToString();
                        string ProduceTime = ProductSet.Tables["data"].Rows[i]["ProduceTime"].ToString();
                        //创造基地字符串
                        BaseSet = dbo.GetDataSet("select * from BaseManage where BaseName='" + basename + "'");
                        if (BaseSet != null && BaseSet.Tables["data"].Rows.Count > 0)
                        {
                            //basestr = "<tr>" + left + 
                            BaseId = BaseSet.Tables["data"].Rows[0][0].ToString();
                            BaseCode = BaseSet.Tables["data"].Rows[0][1].ToString();
                            BaseName = BaseSet.Tables["data"].Rows[0][2].ToString();
                            BaseScale = BaseSet.Tables["data"].Rows[0][3].ToString();
                            ProduceType = BaseSet.Tables["data"].Rows[0][4].ToString();
                            StandardCode = BaseSet.Tables["data"].Rows[0][5].ToString();
                            PeopleName = BaseSet.Tables["data"].Rows[0][6].ToString();
                            PhoneNumber = BaseSet.Tables["data"].Rows[0][7].ToString();
                            BookNumber = BaseSet.Tables["data"].Rows[0][8].ToString();
                            Address = BaseSet.Tables["data"].Rows[0][9].ToString();
                            airreport = BaseSet.Tables["data"].Rows[0]["AirReport"].ToString();
                            waterreport = BaseSet.Tables["data"].Rows[0]["WaterReport"].ToString();
                            soilreport = BaseSet.Tables["data"].Rows[0]["SoilReport"].ToString();
                            ferreport = BaseSet.Tables["data"].Rows[0]["FerReport"].ToString();
                            yaoreport = BaseSet.Tables["data"].Rows[0]["YaoReport"].ToString();
                            checkrecord = BaseSet.Tables["data"].Rows[0]["CheckRecord"].ToString();
                            operaterecord = BaseSet.Tables["data"].Rows[0]["OperateRecord"].ToString();

                        }
                       
                        tempfile = FileStr;
                        //插入数据
                        
                        tempfile = tempfile.Replace("<$BaseCode$>", BaseCode);
                        tempfile = tempfile.Replace("<$PeopleName$>", PeopleName);
                        tempfile = tempfile.Replace("<$PhoneNumber$>", PhoneNumber);
                        tempfile = tempfile.Replace("<$BaseScale$>", BaseScale);
                        tempfile = tempfile.Replace("<$BaseName$>", BaseName);
                        tempfile = tempfile.Replace("<$ProduceType$>", ProduceType);
                        tempfile = tempfile.Replace("<$BookNumber$>", BookNumber);
                        tempfile = tempfile.Replace("<$StandardCode$>", StandardCode);
                        tempfile = tempfile.Replace("<$Address$>", Address);
                        tempfile = tempfile.Replace("<$FeiLiao$>", feiliaostr);
                        tempfile = tempfile.Replace("<$NongYao$>", nongyaostr);
                        tempfile = tempfile.Replace("<$YangFen$>", yangfenstr);
                        //产品信息
                        tempfile = tempfile.Replace("<$ProductName$>", productname);
                        tempfile = tempfile.Replace("<$Code$>", Code);
                        tempfile = tempfile.Replace("<$ProductType$>", ProductType);
                        tempfile = tempfile.Replace("<$ProductScale$>", ProductScale);
                        tempfile = tempfile.Replace("<$ProductCircle$>", ProductCircle);
                        tempfile = tempfile.Replace("<$Package$>", Package);
                        tempfile = tempfile.Replace("<$YearOutPut$>", YearOutPut);
                        tempfile = tempfile.Replace("<$Sales$>", Sales);
                        tempfile = tempfile.Replace("<$ProductStandardCode$>", ProductStandardCode);
                        tempfile = tempfile.Replace("<$ProductIntroductPath$>", ProductIntroductPath);
                        tempfile = tempfile.Replace("<$CookTech$>", CookTech);
                        tempfile = tempfile.Replace("<$OperateRule$>", OperateRule);
                        tempfile = tempfile.Replace("<$QRFile$>", QRPath);
                        tempfile = tempfile.Replace("<$ProductOrder$>", ProductOrder);
                        tempfile = tempfile.Replace("<$ProduceTime$>", ProduceTime);
                        
                        //tempfile = tempfile.Replace("<$Product$>", productstr);
                        //tempfile = tempfile.Replace("<$airreport$>", airreport);
                        //tempfile = tempfile.Replace("<$waterreport$>", waterreport);
                        //tempfile = tempfile.Replace("<$soilreport$>", soilreport);
                        //tempfile = tempfile.Replace("<$ferreport$>", ferreport);
                        //tempfile = tempfile.Replace("<$yaoreport$>", yaoreport);
                        //tempfile = tempfile.Replace("<$checkrecord$>", checkrecord);
                        //tempfile = tempfile.Replace("<$operaterecord$>", operaterecord);

                        //检查是否有附加的检测报告，若有，则替换模板中的<!---->标记
                        DataSet table;
                        dbOperate reportdb = new dbOperate();
                        String replaceStr = "";
                        String reportPath = "";
                        
                        //附加的空气检测报告
                        reportPath = MakeReportStr(BaseId.ToString(),ProductId, "空气检测报告", "<$airreport$>");
                        tempfile = tempfile.Replace("<!--空气检测报告-->", reportPath);

                        //附加的水检测报告
                        reportPath = MakeReportStr(BaseId.ToString(),ProductId, "水检测报告", "<$waterreport$>");
                        tempfile = tempfile.Replace("<!--水检测报告-->", reportPath);
                        //附加的土壤检测报告
                        reportPath = MakeReportStr(BaseId.ToString(),ProductId, "土壤检测报告", "<$soilreport$>");
                        tempfile = tempfile.Replace("<!--土壤检测报告-->", reportPath);
                        //附加的化肥检测报告
                        reportPath = MakeReportStr(BaseId.ToString(),ProductId, "化肥使用记录", "<$ferreport$>");
                        tempfile = tempfile.Replace("<!--化肥使用记录-->", reportPath);

                        //附加化肥使用明细
                        string detail = MakeDetailStr(BaseId.ToString(),ProductId,"化肥使用记录");
                        tempfile = tempfile.Replace("<!--化肥使用记录明细-->", detail);
                        //附加的农药检测报告
                        reportPath = MakeReportStr(BaseId.ToString(),ProductId, "农药使用记录", "<$yaoreport$>");
                        tempfile = tempfile.Replace("<!--农药使用记录-->", reportPath);

                        
                        //附加农药使用明细
                        detail = MakeDetailStr(BaseId.ToString(), ProductId, "农药使用记录");
                        tempfile = tempfile.Replace("<!--农药使用记录明细-->", detail);

                        //附加的三检一标抽检记录
                        reportPath = MakeReportStr(BaseId.ToString(), ProductId,"抽检记录", "<$checkrecord$>");
                        tempfile = tempfile.Replace("<!--三检一标抽检记录-->", reportPath);

                        detail = MakeDetailStr(BaseId.ToString(),ProductId, "抽检记录");
                        tempfile = tempfile.Replace("<!--抽检记录明细-->", detail);

                        //附加的三检一标生产操作记录
                        reportPath = MakeReportStr(BaseId.ToString(), ProductId,"生产操作记录", "<$operaterecord$>");
                        tempfile = tempfile.Replace("<!--三检一标生产操作记录-->", reportPath);

                        detail = MakeDetailStr(BaseId.ToString(),ProductId, "生产操作记录");
                        tempfile = tempfile.Replace("<!--生产操作记录明细-->", detail);


                        sw.Write(tempfile);
                        sw.Flush();
                        sw.Close();
                        fs.Close();
                    }
                    box.AppendText("文件生成完毕\n");
                }
                catch (Exception ex)
                {
                    box.AppendText("文件生成出错，系统异常：" + ex.Message + "\n");
                }
            }

        }
        private String MakeReportStr(string baseid,string productid,string reporttype,string replacetpl)
        {
            DataSet table;
            dbOperate reportdb = new dbOperate();
            String reportPath = "";
            String temp = "";
            table = reportdb.GetDataSet("select * from BaseReport where baseid=" + baseid + " and reporttype='"+reporttype+"' and (productid="+productid+" or productid=0)");
            if (table == null)
                return "";
            temp = "<a class=\"thickbox\" href=\".."+replacetpl+"\"><img src=\".."+replacetpl+"\" class=\"thickbox reportpic\" ></img></a>";
            int index = 0;
            for (index = 0; index < table.Tables[0].Rows.Count; index++)
            {
                String temp1 = temp;
                reportPath += temp1.Replace(replacetpl, table.Tables["data"].Rows[index][2].ToString());
            }
            return reportPath;

        }

        private String MakeDetailStr(string baseid,string productid, string operatetype)
        {
            DataSet table;
            dbOperate detaildb = new dbOperate();
            string sql = "select operateman,operatedate,operatecontent,operatememo,operatetype from operaterecord where baseid=" + baseid + " and operaterecord.operatetype='" + operatetype + "' and ( productid=" + productid + " or productid= 0) order by operatedate asc";
            table = detaildb.GetDataSet(sql);
            if (table == null || table.Tables[0].Rows.Count == 0)
            {
                return "";
                //return "<div class=\"detail\">" + "<h3>" + operatetype + "明细</h3>没有记录</div>";
            }

            String detail = "<div class='detail'>";
            detail += "<h3>" + operatetype + "明细</h3>";
                       
            detail += "<table>";
            detail += "<thead>";
            detail += "<th>操作员</th>";
            detail += "<th>操作时间</th>";
            detail += "<th>操作内容</th>";            
            detail += "<th>备注</th>";
            detail += "</thead>";
            detail += "<tbody>";
           
            int index = 0;
            for (index = 0; index < table.Tables[0].Rows.Count; index++)
            {
                detail += "<tr>";
                detail += "<td>" + table.Tables["data"].Rows[index][0].ToString()+"</td>";
                detail += "<td>" + table.Tables["data"].Rows[index][1].ToString() + "</td>";
                detail += "<td>" + table.Tables["data"].Rows[index][2].ToString() + "</td>";
                detail += "<td>" + table.Tables["data"].Rows[index][3].ToString() + "</td>";
                detail += "</tr>";
            }
            detail += "</tbody>";
            detail += "</table>";
            detail += "</div>";

            return detail;
        }
    }
}
